﻿
var previousExecuteOnServerCall;

var changeTrackerDisabled;

ignoreExecuteOnServer = function () {
    var now = new Date().getTime();

    if (previousExecuteOnServerCall) {
        var ticksSincePrevious = now - previousExecuteOnServerCall;

        if (ticksSincePrevious < 250) {
            return true;
        }
    }

    previousExecuteOnServerCall = now;
    return false;
}

executeOnServer = function (model, url) {
    executeOnServer(model, url, null);
}
executeOnServer = function (model, url, completeFunction) {
    if (ignoreExecuteOnServer()) {
        return;
    }

    changeTrackerDisabled = true;

    $.ajax({
        url: url,
        type: 'POST',
        data: ko.mapping.toJSON(model),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.redirect) {
                changeTrackerDisabled = false;
                location.href = resolveUrl(data.url);
            }
            else {
                ko.mapping.fromJS(data, model);
                changeTrackerDisabled = false;
            }
        },
        error: function (error) {
            changeTrackerDisabled = false;
            alert("There was an error posting the data to the server: " + error.responseText);
        },
        complete: completeFunction
    });

};

resolveUrl = function (url) {
    if (url.indexOf("~/") == 0) {
        url = baseUrl + url.substring(2);
    }
    return url;
};

function hitChangeTracker(viewModel, newValue) {
    if (changeTrackerDisabled) {
        return;
    }
    
    viewModel.isDirty(true);
}
